package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Page;
import com.changgou.search.dao.SkuRepository;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private SkuRepository skuRepository;

    @Autowired
    private ElasticsearchTemplate template;

    //条件查询 搜索面板
    @Override
    public Map<String, Object> searchQuery(Map<String, String> searchMap) {

        Map<String, Object> resultMap = new HashMap<>();

        //判断用户是否输入查询条件
        if (searchMap != null) {
            //根据用户输入的数据构建查询条件
            //构建queryBuilder对象
            NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
            //构建多条件查询对象
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

            //封装查询对象
            //根据用户输入的关键词进行匹配查询
            String keyword = searchMap.get("keyword");
            if (StringUtils.isNotEmpty(keyword)) {

                //关键字匹配分类
                boolQueryBuilder.should(QueryBuilders.termQuery("categoryName", keyword));

                //关键字匹配对应的品牌
                boolQueryBuilder.should(QueryBuilders.termQuery("brandName", keyword));

                //关键字匹配商品名称
                boolQueryBuilder.should(QueryBuilders.queryStringQuery(keyword).defaultField("name"));
            }

            //根据分类对查询结果进行过滤
            String categoryName = searchMap.get("categoryName");
            if (StringUtils.isNotEmpty(categoryName)) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("categoryName", categoryName));
            }

            //根据品牌对查询结果进行过滤
            String brandName = searchMap.get("brandName");
            if (StringUtils.isNotEmpty(brandName)) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brandName", brandName));
            }

            //根据规格进行过滤
            for (String key : searchMap.keySet()) {
                //判断是否是规格参数 如果是规格参数需要添加规格过滤条件
                if (key.startsWith("spec_")) {
                    boolQueryBuilder.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", searchMap.get(key)));
                }
            }

            //根据价格区间进行过滤
            String price = searchMap.get("price");
            if (StringUtils.isNotEmpty(price)) {
                String[] strs = price.split("-");
                //如果价格参数的第一部分不为0 代表有最低价格 匹配商品价格大于最低价格的商品

                /*if (!"0".equals(strs[0])){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(strs[0]));
                }*/

                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(strs[0]));
                //如果价格参数的第二部分不为* 代表有最高价格 匹配商品价格小于最高价格的商品
                if (!"*".equals(strs[1])) {
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(strs[1]));
                }
            }

            //设置聚合条件   搜索面板数据
            //分类面板数据查询条件
            String skuCategory = "skuCategory";
            queryBuilder.addAggregation(AggregationBuilders.terms(skuCategory).field("categoryName"));
            //品牌面板数据查询条件
            String skuBrand = "skuBrand";
            queryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
            //规格面板数据查询条件
            String skuSpec = "skuSpec";
            queryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //分页查询
            String pageNum = searchMap.get("pageNum");
            String pageSize = searchMap.get("pageSize");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //构建分页查询条件
            queryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));

            //排序查询
            String sortField = searchMap.get("sortField");//排序字段
            String sortRule = searchMap.get("sortRule");//排序规则

            //排序字段不为空的情况下 需要进行排序
            if (StringUtils.isNotEmpty(sortField)) {
                queryBuilder.withSort(SortBuilders.fieldSort(sortField).order("ASC".equals(sortRule) ? SortOrder.ASC : SortOrder.DESC));
            }

            queryBuilder.withQuery(boolQueryBuilder);

            //设置高亮查询的域以及标签
            HighlightBuilder.Field field = new HighlightBuilder.Field("name").preTags("<span style='color=red'>").postTags("</span>");
            queryBuilder.withHighlightFields(field);

            //执行搜索(不会返回高亮数据显示的)
//            Page<SkuInfo> skuInfos = skuRepository.search(queryBuilder.build());

            AggregatedPage<SkuInfo> skuInfos = template.queryForPage(queryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                //searchResponse 搜索响应数据 匹配的结果集全部在里面
                //aClass 数据封装的类型
                //pageable 分页参数
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<SkuInfo> list = new ArrayList<>();
                    //获取命中数据
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        //遍历获取每一条命中数据
                        for (SearchHit hit : hits) {
                            String sourceAsString = hit.getSourceAsString();
                            //把命中数据转为skuInfo对象
                            SkuInfo skuInfo = JSON.parseObject(sourceAsString, SkuInfo.class);
                            //获取高亮域以及高亮片段
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                //获取高亮片段
                                Text[] names = highlightFields.get("name").getFragments();
                                //把高亮数据设置到skuInfo对象中
                                skuInfo.setName(names[0].toString());
                            }
                            //将处理完成之后 具有高亮数据的skuInfo添加到集合中
                            list.add(skuInfo);
                        }
                    }

                    return new AggregatedPageImpl(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            //获取聚合数据  分类数据
            StringTerms categoryTerms = skuInfos.getAggregations().get(skuCategory);
            List<String> categoryList = new ArrayList<>();
            categoryTerms.getBuckets().forEach(bucket -> {
                categoryList.add(bucket.getKeyAsString());
            });

            //获取聚合数据  品牌数据
            StringTerms brandTerms = skuInfos.getAggregations().get(skuBrand);
            List<String> brandList = new ArrayList<>();
            brandTerms.getBuckets().forEach(bucket -> {
                brandList.add(bucket.getKeyAsString());
            });

            //获取聚合数据  品牌数据
            StringTerms specTerms = skuInfos.getAggregations().get(skuSpec);
            List<String> specList = new ArrayList<>();
            specTerms.getBuckets().forEach(bucket -> {
                specList.add(bucket.getKeyAsString());
            });

            Map<String, Set<String>> specMap = new HashMap<>();
            for (String spec : specList) {
                //将规格字符串转化为map集合
                Map<String, String> map = JSON.parseObject(spec, Map.class);
                //遍历map中的每一个键值对
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    //将遍历获取到的键值对存放到外部的map集合中
                    if (specMap.get(entry.getKey()) == null) {
                        Set<String> values = new HashSet<>();
                        values.add(entry.getValue());
                        specMap.put(entry.getKey(), values);
                        continue;
                    }

                    //specMap已经存在数据
                    specMap.get(entry.getKey()).add(entry.getValue());
                }
            }

            //封装返回数据
            resultMap.put("skuList", skuInfos.getContent());
            //获取命中数据总条数
            resultMap.put("total", skuInfos.getTotalElements());
            //总页数
            resultMap.put("totalPages", skuInfos.getTotalPages());
            resultMap.put("pageNum", Integer.parseInt(pageNum));
            resultMap.put("pageSize", Integer.parseInt(pageSize));
            resultMap.put("categoryList", categoryList);
            resultMap.put("brandList", brandList);
            resultMap.put("specMap", specMap);
        }
        return resultMap;
    }


    //展示所有商品

//    public Map<String, Object> findAll() {
//        Map<String, Object> resultMap = new HashMap<>();
//        //构建queryBuilder对象
//        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//        //构建多条件查询对象
//        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//        //构建分页查询条件
//        queryBuilder.withPageable(PageRequest.of(0, 20));
//        queryBuilder.withQuery(boolQueryBuilder);
//
//        return resultMap;
//    }
}
